<?php

namespace app\api\controller;

use helper\JwtHelper;
use think\App;
use traits\controller\JumpTraits;
use traits\controller\QueryTraits;

/**
 * 控制器基础类
 */
abstract class Base
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var App
     */
    protected $app;

    /**
     * 会员资料
     * @var array
     */
    protected $loginInfo;
    protected $adminInfo;
    protected $role_ids;

    /**
     * singKey
     * @var string
     */
    protected $signKey = 'u3oaJz9FhJAb';

    use JumpTraits;
    use QueryTraits;

    /**
     * 构造方法
     * Base constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $this->app = app();
        $this->request = $this->app->request;
        //$this->checkCsrfToken();
    }

    /**
     * 校验md5签名
     * @throws \Exception
     */
    public function checkCsrfToken()
    {
        $time = time();
        $timestamp = $this->request->param('timestamp');
        $csrfToken = $this->request->header('x-csrf-token');
        if (empty($time) || empty($csrfToken)) //exception('签名校验错误');
            $this->result([],'签名校验错误',0);
        if (($time - $timestamp) > 600) //exception('请求超时!');
            $this->result([],'请求超时',0);
        if (md5($this->signKey . $timestamp) != $csrfToken) //exception('签名不正确!');
            $this->result([],'签名不正确',0);
    }

    /**
     * 验证登录状态
     * @throws \Exception
     */
    public function checkLogin()
    {
        $token = $this->request->header("authorization");

        try {
            JwtHelper::make()->verfiyToken($token);
            $info = JwtHelper::make()->all();
            if(empty($info['data']['role_ids'])){
                $this->result('该用户还未设置岗位，请联系管理员设置后再登录!', "LOGIN_ERROR", 0);exit;
            }
            $this->loginInfo = $info['data'];
            $this->role_ids = explode(',',$info['data']['role_ids']);
        } catch (\Exception $e) {
            $this->result('登录超时', "LOGIN_ERROR", 0);
        }
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @param bool $failException 是否批量验证
     * @return bool|true
     */
    protected function validate(array $data, $validate, array $message = [], $batch = false, $failException = true)
    {
        return validate($validate, $message, $batch, $failException)->check($data);
    }

}
